package com.yuchen.ishop.service.admin.goods.impl;

import java.util.Map;

import com.yuchen.ishop.service.admin.goods.GoodsService;
import org.apache.commons.lang.StringUtils;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yuchen.core.MyPager;
import com.yuchen.core.jdbc.BaseDao;
import com.yuchen.ishop.entity.Goods;

@Service
@Transactional
public class GoodsServiceImpl implements GoodsService {

	@Autowired
    private BaseDao dao;
  
    @Override
    public MyPager findPage(Integer pageSize, Integer pageNo, Map<String, Object> map) {
    	MyPager pager = new MyPager();
    	pager.setPageSize(pageSize);
    	pager.setPageNo(pageNo);
    	StringBuilder sql = new StringBuilder();
    	sql.append("select t.id id, t.name name, t.price price,t.recommend recommend, t.create_time create_time, t2.name  sellername ");
    	sql.append("from t_goods t, t_sellers t2 ");
    	sql.append("where t.seller_id = t2.id ");
		if(null != map && map.size()>0) {
			if (StringUtils.isNotBlank((String) map.get("name"))) {
				sql.append(" and t.name like concat(@name, '%') ");
			}
			if (StringUtils.isNotBlank((String) map.get("date_s"))) {
				sql.append(" and t.create_time >= @date_s ");
			}
			if (StringUtils.isNotBlank((String) map.get("date_e"))) {
				sql.append(" and t.create_time <= @date_e ");
			}
			if (map.get("state") != null) {
				sql.append(" and t.state = @state ");
			}
			if(map.get("publishState")!=null){
				sql.append(" and t.publish_state = @publishState ");
			}
			if(map.get("recommend")!=null){
				sql.append(" and t.recommend = @recommend ");
			}
		}
        return dao.queryPager(sql.toString(), map, pager);
    }
    
    public void doAuditPass(Long[] ids){
    	for(Long id : ids){
    		Goods t = new Goods();
    		t.setId(id);
    		t.setState(1L);
    		update(t, true);
    	}
    }

	@Override
	public Boolean recommend(Long id, Long recommend) {
		int count = dao.update(Goods.class, Chain.make("recommend",recommend), Cnd.where("id","=",id));
		return true;
	}

	@Override
	public Boolean changeState(Long id, Long state) {
		int count = dao.update(Goods.class, Chain.make("state",state), Cnd.where("id","=",id));
		return true;
	}

	@Override
	public Goods insert(Goods t) {
		return dao.insert(t);
	}

	@Override
	public int update(Goods t,boolean isIgnoreNull) {
		if(isIgnoreNull)
			return dao.updateIgnoreNull(t);
		return dao.update(t);
	}


	@Override
	public Goods getById(Long id) {
		return dao.fetch(Goods.class, id);
	}

	@Override
	public int delete(Long id) {
		return dao.delete(Goods.class, id);
	}
}
